package com.controller;

import com.bean.UserBean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@SessionAttributes(types = {UserBean.class})
@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/toReg")
    public String toReg() {
        return "regist.jsp";
    }

    @RequestMapping("/doRegister")
    public String register(@RequestParam("username") String username,
                           @RequestParam("password") String pwd, Model model) {
        System.out.println("通过注册页面传递的数据：uname=" + username + "pwd=" + pwd);
        UserBean user = new UserBean();
        user.setUsername(username);
        user.setPassword(pwd);
        model.addAttribute("user",user);
        return "forward:toLogin";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login.jsp";
    }

    @RequestMapping("/login")
    public ModelAndView doLogin(@RequestParam("username") String uname, @RequestParam("password") String pwd,
                                @SessionAttribute("user") UserBean userBean, ModelAndView view) {
        System.out.println("通过登录界面传递的参数：从jsp中传递的数据有username=" + uname + "密码=" + pwd +
                "从Session中传递的数据用户名="
                + userBean.getUsername() + "password=" + userBean.getPassword());
        String msg ;
        if (uname.equals(userBean.getUsername()) && pwd.equals(userBean.getPassword())) {
            msg = "登录成功,欢迎进入系统";
        } else {
            msg = "登录失败，用户名或者密码不正确";
        }
        UserBean loginBean = new UserBean();
        loginBean.setPassword(pwd);
        loginBean.setUsername(uname);
        view.addObject("msg",msg);
        view.addObject("user",loginBean);
        view.setViewName("result.jsp");

//        return "result.jsp";
        return view;
    }

}
